<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>table模块快速使用</title>
  <link rel="stylesheet" href="../layui/css/layui.css" media="all">
</head>
<body>
 
<table id="demo" lay-filter="test" ></table>

<!--工具条-->
<script type="text/html" id="barDemo">
  <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<!--热销-->
<script type="text/html" id="checkboxTpl">
  <input type="checkbox" name="is_best" goods_id="{{ d.gid }}" lay-skin="switch" lay-text="Y|N" value="{{d.is_best == 'yes' ? 'yes' : 'no'}}" title="锁定" lay-filter="lockDemo" {{ d.is_best == 'yes' ? 'checked' : '' }}>
</script>
<!--回收-->
<script type="text/html" id="checkboxRecycle">
  <input type="checkbox" name="recycle" goods_id="{{ d.gid }}" lay-skin="switch" lay-text="Y|N" value="{{d.recycle == 'yes' ? 'yes' : 'no'}}" title="锁定" lay-filter="lockDemo2" {{ d.recycle == 'yes' ? 'checked' : '' }}>
</script>
<!--上架-->
<script type="text/html" id="checkboxStatus">
  <input type="checkbox" name="status" goods_id="{{ d.gid }}" lay-skin="switch" lay-text="Y|N" value="{{d.status == 'yes' ? 'yes' : 'no'}}" title="锁定" lay-filter="lockDemo3" {{ d.status == 'yes' ? 'checked' : '' }}>
</script>
<!-- 头部工具栏 -->
<script type="text/html" id="toolbarDemo">
  <div class="layui-btn-container">
    <button class="layui-btn layui-btn-sm" lay-event="getCheckData">添加商品</button>
    <!-- <button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>
    <button class="layui-btn layui-btn-sm" lay-event="isAll">验证是否全选</button> -->
  </div>
</script>


 
<script src="../layui/layui.js"></script>
<script src="../js/ajax.js"></script>
<script>

layui.use('table', function(){
  var table = layui.table
  ,form = layui.form;
  
  //表格初始化
  table.render({
    elem: '#demo'
    ,height: 400
    ,url: './public/select_limit.php?table=t_goods&id=gid' //数据接口
    ,page: true //开启分页
    ,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
    ,cols: [[ //表头
      {field: 'gid', title: 'ID', width:80, sort: true, fixed: 'left'}
      ,{field: 'gname', title: '商品名称', width:160}
      ,{field: 'price', title: '价格', width:80, sort: true}
      ,{field: 'status', title: '上架', width:80, templet: '#checkboxStatus'} 
      ,{field: 'description', title: '描述', width: 180}
      ,{field: 'stock', title: '库存', width: 80, sort: true}
      ,{field: 'identifier', title: '商品编号', width: 100, sort: true}
      ,{field: 'recycle', title: '回收', width: 80, templet: '#checkboxRecycle'}
      ,{field: 'cid', title: '分类', width: 80, sort: true}
      ,{field: 'is_best', title: '热销', width: 80, sort: true, templet: '#checkboxTpl'}
      ,{field: '', title: '操作', width: 135, sort: true, toolbar: '#barDemo'}
    ]]
    ,done: function(res, curr, count){ 
        //console.log(res);   // 后台返回来的数据
        //console.log(curr);
        //console.log(count);
    }
  });


  //头工具栏事件
  table.on('toolbar(test)', function(obj){
    switch(obj.event){
      case 'getCheckData':
        layer.open({
          type: 2,
          title: "添加商品",
          area: ['520px', '430px'],
          content: './widget/goods-m-add.html', //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
          success: function(layero, index){
            var body = layer.getChildFrame('body', index);
            var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
            //console.log(body.html()) //得到iframe页的body内容
            console.log(table.cache.demo[0])
            //var a = table.cache.demo[0];
            table.cache.demo.unshift(table.cache.demo[0]);
            console.log(table.cache)
            
          }
        });
      break;
    };
  });



  //监听工具条 
table.on('tool(test)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"

  var data = obj.data; //获得当前行数据
  var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
  var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）

  var inputIs_best = tr[0].querySelector('input[name="is_best"]'),
      inputRecycle = tr[0].querySelector('input[name="recycle"]'),
      inputsTatus = tr[0].querySelector('input[name="status"]');

  data.is_best = inputIs_best.value;
  data.recycle = inputRecycle.value;
  data.status = inputsTatus.value;

  if(layEvent === 'detail'){ //查看
    //do somehing
  } else if(layEvent === 'del'){ //删除
    layer.confirm('确定删除吗', function(index){
      // 开启加载动画
      var index2 = layer.load(2, {time: 10*1000});
     
      layer.close(index);
       //向服务端发送删除指令
      ajax({   
        url: './public/del_one.php',
        data: {
          table: 't_goods',
          id_name: 'gid',
          id: data.gid
        },
        method: 'post',
        success: function(res){
          // 关闭加载动画
          layer.close(index2);     
          if(res == 1){
            layer.msg('删除成功'); 
            obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
          }else{
            layer.msg('删除失败'); 
          }
        }
      });
  
    });
  } else if(layEvent === 'edit'){ //编辑
    //do something
  
    layer.open({
      type: 2,
      title: "修改商品",
      area: ['520px', '430px'],
      content: './widget/goods-m-edit.html', //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
      success: function(layero, index){
        var body = layer.getChildFrame('body', index);
        var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
        //console.log(body.html()) //得到iframe页的body内容
        
        // 为子页面表单赋值
        body.find('input[name="gname"]').val(data.gname);
        body.find('input[name="price"]').val(data.price);
        if(data.status == 'yes'){
          body.find('input[name="status"]').prop('checked', 'checked');
        }
        body.find('input[name="status"]').val(data.status);
        body.find('input[name="description"]').val(data.description);
        body.find('input[name="stock"]').val(data.stock);
        body.find('input[name="identifier"]').val(data.identifier);
        if(data.recycle == 'yes'){
          body.find('input[name="recycle"]').prop('checked', 'checked');
        }
        body.find('input[name="recycle"]').val(data.recycle);
        body.find('input[name="cid"]').val(data.cid);
        if(data.is_best == 'yes'){
          body.find('input[name="is_best"]').prop('checked', 'checked');
        }
        body.find('input[name="is_best"]').val(data.is_best);
 
        // 向子iframe传值
        iframeWin.child(data, function(newData){
            //同步更新缓存对应的值
            obj.update({
                gname: newData.gname,
                description: newData.description,
                identifier: newData.identifier,
                is_best: newData.is_best,
                price: newData.price,
                recycle: newData.recycle,
                status: newData.status,
                stock: newData.stock,
                cid: newData.cid
            });

            //更新渲染表单元素
            form.render('checkbox');
        }); 

      }
    });
    
    
  } else if(layEvent === 'LAYTABLE_TIPS'){
    layer.alert('Hi，头部工具栏扩展的右侧图标。');
  }
  
});





//监听锁定操作
form.on('switch(lockDemo)', function(obj){
  switchOn(this,{
    table: 't_goods',
    id_name: 'gid'
  });
    //console.log(obj)
    //console.log(this)
    //layer.tips(this.value + ' ' + this.name + '：'+ obj.elem.checked, obj.othis);
   // console.log(obj.value)
});
form.on('switch(lockDemo2)', function(obj){
  switchOn(this);
});
form.on('switch(lockDemo3)', function(obj){
  switchOn(this);
});

function switchOn(This, obj={}){
  var index2 = layer.load(2, {time: 10*1000});
  var table = obj.table || 't_goods',
        id_name = obj.id_name || 'gid';
    if(This.checked){
      This.value = 'yes';
    }else{
      This.value = 'no';
    }
    
    var id = This.attributes['goods_id'].value;
    var field = This.name;
    ajax({
      url: './public/form_switch.php',
      data: {
          table: table,
          id_name: id_name,
          id: id,
          field: field,
          field_val: This.value
      },
      method: 'post',
      success: function(res){
          // 关闭加载动画
          layer.close(index2);     
      }
    });
}
   

  
});
  
</script>
</body>
</html>



